//从axios框架导入axios组件
import { getTokenName, messageTip, removeToken, messageConfirm } from "@/util/util";
import axios from "axios";
import { ElMessageBox } from "element-plus";


//定义后端接口地址的前缀
axios.defaults.baseURL = "http://localhost:8089";

//axios.defaults.baseURL = "http://192.168.253.131:8089";

export function doGet(url, params) {
  return axios({
    method: "get",
    url: url,
    params: params, //{name: "对的", age: 22},
    dataType: "json"
  })
}

export function doPost(url, data) {
  return axios({
    method: "post",
    url: url,
    data: data, //{name: "好的呢", age: 22},
    dataType: "json"
  })
}

export function doPut(url, data) {
  return axios({
    method: "put",
    url: url,
    data: data, //{name:"好的呢", age: 22},
    dataType: "json"
  })
}

export function doDelete(url, params) {
  return axios({
    method: "delete",
    url: url,
    params: params, //{name: "对的", age: 22},
    dataType: "json"
  })
}

//请求拦截器
axios.interceptors.request.use((config) => {
  //从sessionStorage获取token
  let token = window.sessionStorage.getItem(getTokenName())
  if (!token) {
    //从localStorage获取token
    token = window.localStorage.getItem(getTokenName())
    if (token) {
      config.headers['rememberMe'] = true
    }
  }

  if (token) {
    config.headers['Authorization'] = token
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use((response) => {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么，拦截token验证的结果，进行相应的提示和页面跳转
  if (response.data.code >= 500) { //code大于900说明是token验证未通过
    //给前端用户提示，并且跳转页面
    messageConfirm(response.data.msg + ",是否重新去登录").then(() => {
      //点击确定跳转到登录页面
      removeToken();
      window.location.href = "/";
    }).catch(() => {
      messageTip("取消去登录", "warning")
    })
    //这里出现异常直接退出，不返回数据，否则退出登录异常又弹出一个框
    return;
  }
  return response
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  return Promise.reject(error);
});